﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodWorx.CMS.TemplateLanguage
{
    public class HtmlResult
    {
        public HtmlResult()
        {
            this.PreContent = new StringBuilder();
            this.PostContent = new StringBuilder();
        }

        private Dictionary<string, string> attributes = new Dictionary<string, string>();

        public StringBuilder PreContent
        {
            get; private set;
        }

        public StringBuilder PostContent
        {
            get;
            private set;
        }

        private string tag;

        public HtmlResult SetTag(string tag)
        {
            this.tag = tag;
            this.BuildHtml();
            return this;
        }

        private void BuildHtml()
        {
            if(!string.IsNullOrEmpty(this.tag))
            {
                this.PreContent = new StringBuilder("<" + this.tag + " ");
                this.PostContent = new StringBuilder();
                foreach(var attr in this.attributes.Keys)
                {
                    this.PreContent.Append(attr + "=\"" + this.attributes[attr] + "\" ");
                }
                this.PreContent.Append(">");

                this.PostContent.Append("</" + this.tag + ">");
            }
        }

        public object Content { get; set; }

        public HtmlResult AddAttribute(string parameter, string value)
        {
            this.attributes.Add(parameter, value);
            this.BuildHtml();
            return this;
        }

        public override string ToString()
        {
            this.BuildHtml();
            if(this.Content != null)
                return (this.PreContent.ToString()) + (this.Content.ToString()) + (this.PostContent.ToString());
            else
                return (this.PreContent.ToString()) + (this.PostContent.ToString());
        }
    }
}
